# 角色-权限绑定服务层
from backend.models.role_permission import RolePermission
from backend.models.role import Role
from backend.models.permission import Permission
from backend.infrastructure.database import db

def get_role_permissions(role_id):
    perms = RolePermission.query.filter_by(role_id=role_id).all()
    perm_ids = [rp.permission_id for rp in perms]
    permissions = Permission.query.filter(Permission.id.in_(perm_ids)).all()
    return [p.to_dict() for p in permissions]

def set_role_permissions(role_id, permission_ids):
    # 先删除原有绑定
    RolePermission.query.filter_by(role_id=role_id).delete()
    # 批量添加新绑定
    for pid in permission_ids:
        rp = RolePermission(role_id=role_id, permission_id=pid)
        db.session.add(rp)
    db.session.commit()
    return {'success': True}
